<?php

namespace App\Models\Traits;

use Carbon\Carbon;
use App\Models\GoldRecord;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

trait HasUserStormPendingCache
{
	public function pendingRecordsCacheKey(): string
	{
		return "user_{$this->id}_pending_gold_records";
	}

	public function markRecordCacheReselling($cacheId)
	{
		Redis::hMset($cacheId, ['is_resell_applying' => true]);
	}

	public function markRecordCacheSpliting($cacheId)
	{
		Redis::hMset($cacheId, ['is_split_applying' => true]);
	}

	public function markRecordCacheTaking($cacheId)
	{
		Redis::hMset($cacheId, ['is_take_applying' => true]);
	}

	public function markRecordCacheAsResell(GoldRecord $record)
	{
		if ($record->user->is_mock) return;

		Redis::transaction(function () use ($record) {
			$cacheId = $record->cacheKey();
            Redis::hMset($cacheId, [
                'resell_all_price' => $record->resell_all_price,
                'is_resell_applying' => false,
                'has_applied_to_resell' => true,
                'to_resell_applied_at' => Carbon::now(),
                'next_resell_at' => $record->nextResellAt(),
            ]);
			$this->addRecordToRunningCache($cacheId);
			$this->delRecordFromPendingCache($cacheId);
			Log::debug("Pending record cache: {$cacheId} resell");
		});
	}

	public function markRecordCacheAsSplit(GoldRecord $record)
	{
		if ($record->user->is_mock) return;

        Redis::transaction(function () use ($record) {
            $cacheId = $record->cacheKey();
            Redis::hMset($cacheId, [
                'resell_all_price' => $record->resell_all_price,
                'is_split_applying' => false,
                'has_applied_to_split' => true,
                'to_split_applied_at' => Carbon::now(),
                'next_resell_at' => $record->nextResellAt(),
            ]);
            $this->addRecordToRunningCache($cacheId);
            $this->delRecordFromPendingCache($cacheId);
        });
	}

	public function markRecordCacheAsTake(GoldRecord $record)
	{
		if ($record->user->is_mock) return;

		Redis::transaction(function () use ($record) {
		    $cacheId = $record->cacheKey();
			Redis::hMset($cacheId, [
				'resell_all_price' => $record->resell_all_price,
				'is_take_applying' => false,
				'has_applied_to_take' => true,
				'to_take_applied_at' => Carbon::now(),
			]);
            $this->delRecordFromPendingCache($cacheId);
            $this->addRecordToFinishedCache($cacheId);
			Log::debug("Pending record cache: {$cacheId} take");
		});
	}

	public function addRecordToPendingCache($cacheId)
	{
		Redis::zAdd($this->pendingRecordsCacheKey(), 1, $cacheId);
	}

	public function delRecordFromPendingCache($cacheId)
	{
		Redis::zRem($this->pendingRecordsCacheKey(), $cacheId);
	}

	public function isRecordInPendingCache($cacheId): bool
	{
		return Redis::zScore($this->pendingRecordsCacheKey(), $cacheId) == 1;
	}
}
